# plugs/reload.py
#
#

""" reload/unload plugins """

__copyright__ = 'this file is in the public domain'

from ommbot.world import add_cmnd, add_example, get_plugs, get_config
import os

def handle_reload(bot, ievent):
    """ reload <plugin> .. reload a plugin """
    try:
        plug = ievent.args[0].lower()
    except IndexError:
        ievent.missing('<plugin>')
        return
    if plug == 'config':
        config = get_config()
        if config:
            config.reload()
            ievent.reply('config reloaded')
        else:
            ievent.reply('config not enabled')
        return
    plugs = get_plugs()
    plugpaths = plugs.plugpaths
    got = 0
    if 'myplugs' in plugpaths:
        if os.path.isfile('myplugs/%s.py' % plug):
            if plugs.reload('myplugs', plug):
                got = 1
    if not got:
        for i in plugpaths:
            if os.path.isfile('%s/%s.py' % (i, plug)):
                if plugs.reload(i, plug):
                    got = 1
    if got:
        ievent.reply('%s reloaded' % plug)
    else:
        ievent.reply("error reloading %s plugin" % plug)

add_cmnd('reload', handle_reload, 'OPER')
add_example('reload', 'reload <plugin>', 'reload core')

def handle_unload(bot, ievent):
    """ unload <plugin> .. unload a plugin """
    try:
        what = ievent.args[0].lower()
    except IndexError:
        ievent.missing('<plugin>')
        return
    if not plugs.exist(what):
        ievent.reply('there is no %s module' % what)
        return
    if plugs.unload(what):
        plugs.disable(what)
        ievent.reply("%s unloaded and disabled" % what)
    else:
        ievent.reply("%s unload failed" % what)

add_cmnd('unload', handle_unload, 'OPER')
add_example('unload', 'unload <plugin>', 'unload test')
